package com.handpay.nocardpay.baselibrary.main.mine.view.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.bankmanager.view.fragment.BankManagerFragment;
import com.handpay.nocardpay.baselibrary.bill.view.BillFragment;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.lottery.LotteryFragment;
import com.handpay.nocardpay.baselibrary.lottery.model.bean.LotteryStatus;
import com.handpay.nocardpay.baselibrary.lottery.view.ILotteryView;
import com.handpay.nocardpay.baselibrary.main.mine.MainFragment;
import com.handpay.nocardpay.baselibrary.main.mine.model.bean.MerchInfo;
import com.handpay.nocardpay.baselibrary.main.mine.presenter.MinePresenterImpl;
import com.handpay.nocardpay.baselibrary.main.mine.view.IMerchInfoView;
import com.handpay.nocardpay.baselibrary.main.mine.view.IRefreshMerchInfoListener;
import com.handpay.nocardpay.baselibrary.notification.push.NoticeListener;
import com.handpay.nocardpay.baselibrary.notification.push.NoticePushFactory;
import com.handpay.nocardpay.baselibrary.notification.view.activity.NoticeActivity;
import com.handpay.nocardpay.baselibrary.qualificationinfo.view.fragment.IDCardSupplementFragment;
import com.handpay.nocardpay.baselibrary.qualificationinfo.view.fragment.QualificationStatuInfoFragment;
import com.handpay.nocardpay.baselibrary.raindrops.RainDropsFragment;
import com.handpay.nocardpay.baselibrary.recommendercod.view.fragment.RecommenderCodeFragment;
import com.handpay.nocardpay.baselibrary.setting.view.fragment.SettingFragment;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.handpay.nocardpay.baselibrary.widget.CustomTextView;
import com.handpay.nocardpay.baselibrary.widget.DisplayUtil;
import com.yuyh.library.EasyGuide;
import com.yuyh.library.support.HShape;
import com.yuyh.library.support.OnStateChangedListener;

import java.util.HashMap;

import me.yokeyword.fragmentation.ISupportFragment;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sxshi on 2017/8/9.
 */
public class MineFragment extends BaseFragment implements IMerchInfoView, NoticeListener, ILotteryView {
    private SupportFragment[] mFragments = new SupportFragment[2];
    //资质未提交，审核中，审核失败
    public static final int NO_QUALIFICATION = 0;
    //资质审核成功
    public static final int YES_QUALIFICATION = 1;
    private CustomTextView mBasicinfo, mLimit, mNotice, mBankManager, ctv_bill, ctv_recommender_code, ctv_supplementcard, ctv_lottery, ctv_smartpay;
    private CustomTextView ctv_setting;

    public static String newBankFlag = "1";
    private MinePresenterImpl minePresenter;
    private MerchInfo mMerchinfo;
    /**
     * 添加代还信用卡按钮
     */
    private EasyGuide easyGuide;
    private IRefreshMerchInfoListener merchInfoListener;

    public void setMerchInfoListener(IRefreshMerchInfoListener merchInfoListener) {
        this.merchInfoListener = merchInfoListener;
    }

    public static MineFragment newInstance() {
        Bundle args = new Bundle();
        MineFragment fragment = new MineFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main_mine;
    }

    @Override
    public void initView(View view) {
        mBasicinfo = (CustomTextView) view.findViewById(R.id.basicinfo);
        mLimit = (CustomTextView) view.findViewById(R.id.ctv_limit);
        mNotice = (CustomTextView) view.findViewById(R.id.ctv_notice);
        mBankManager = (CustomTextView) view.findViewById(R.id.ctv_bankmanager);
        ctv_bill = (CustomTextView) view.findViewById(R.id.ctv_bill);
        ctv_recommender_code = (CustomTextView) view.findViewById(R.id.ctv_recommender_code);
        ctv_supplementcard = (CustomTextView) view.findViewById(R.id.ctv_supplementcard);
        ctv_setting = (CustomTextView) view.findViewById(R.id.ctv_setting);
        ctv_lottery = (CustomTextView) view.findViewById(R.id.ctv_lottery);
        ctv_smartpay = (CustomTextView) view.findViewById(R.id.ctv_smartpay);
    }


    @Override
    public void initListener() {
        mBasicinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkUserStatus(BasicInfoFragment.newInstance());
            }
        });
        mLimit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainFragment) getParentFragment()).start(DayLimitFragment.newInstance());
            }
        });
        mNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(_mActivity, NoticeActivity.class));
            }
        });
        mBankManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkUserStatus(BankManagerFragment.newInstance(mMerchinfo));
            }
        });
        ctv_bill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainFragment) getParentFragment()).start(BillFragment.newInstance());
            }
        });

        ctv_recommender_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkUserStatus(RecommenderCodeFragment.newInstance());
            }
        });
        ctv_supplementcard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainFragment) getParentFragment()).start(IDCardSupplementFragment.newInstance());
            }
        });
        ctv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainFragment) getParentFragment()).start(SettingFragment.newInstance());
            }
        });
        ctv_lottery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {

                    ((MainFragment) getParentFragment()).start(LotteryFragment.newInstance());
                } else {
                    DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.no_success_qualification), false);
                }
            }
        });
//        ctv_smartpay.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ((MainFragment) getParentFragment()).start(SmartRePayFragment.newInstance());
////                dotest(v);
//            }
//        });
    }

    /**
     * 检测用户状态【未提交-提示引导提交，失败或者审核中进入QualificationStatuInfoFragment】
     */
    private void checkUserStatus(ISupportFragment tagetFragment) {
        if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
            DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.no_submit_qualification), _mActivity.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }, _mActivity.getString(R.string.dialog_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ((MainFragment) getParentFragment()).start(QualificationStatuInfoFragment.newInstance());
                }
            });
        } else if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            ((MainFragment) getParentFragment()).start(tagetFragment);
        } else {
            ((MainFragment) getParentFragment()).start(QualificationStatuInfoFragment.newInstance());
        }
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        minePresenter = new MinePresenterImpl(_mActivity);
        minePresenter.setiMerchInfoView(this);
        minePresenter.setLotteryView(this);
        NoticePushFactory.with().registerNoticeListener(this);
        //将头部Fragment 加载到内存中
        SupportFragment noQualificationFragment = findFragment(NoQualificationFragment.class);
        if (noQualificationFragment == null) {
            mFragments[NO_QUALIFICATION] = NoQualificationFragment.newInstance();
            mFragments[YES_QUALIFICATION] = YesQualificationFragment.newInstance();
            loadMultipleRootFragment(R.id.fl_heald_container, NO_QUALIFICATION, mFragments[NO_QUALIFICATION], mFragments[YES_QUALIFICATION]);
        } else {
            mFragments[NO_QUALIFICATION] = noQualificationFragment;
            mFragments[YES_QUALIFICATION] = findFragment(YesQualificationFragment.class);
        }
        //首次界面加载到内存的时候根据用户状态显示相应的界面
        if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.FAIL) {
            showHideFragment(mFragments[NO_QUALIFICATION], mFragments[YES_QUALIFICATION]);
        } else if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            showHideFragment(mFragments[YES_QUALIFICATION], mFragments[NO_QUALIFICATION]);
        }
    }

    @Override
    public void onSupportVisible() {
//        HPLog.d(HPLog.SSX_TAG, "onSupportVisible");
        super.onSupportVisible();
        String certNoFlag = AccountUtils.getCertNoExporyStatus(_mActivity);
//        HPLog.i(HPLog.LFP_TAG, "certNoFlag:" + certNoFlag);
        if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            //待补件和审核失败都显示
            if (AccountUtils.Account.CERTNO_SUCCESS.equals(certNoFlag)
                    || AccountUtils.Account.CERTNO_NOSTATUS.equals(certNoFlag) || AccountUtils.Account.CERTNO_CHECKING.equals(certNoFlag)) {
                ctv_supplementcard.setVisibility(View.GONE);
            } else {
                ctv_supplementcard.setVisibility(View.VISIBLE);
            }
        }
        if (AccountUtils.getAccountStatus(_mActivity) != AccountUtils.AccountStatus.NOUPLOAD) {
            //只有用戶提交了资质才去 获取商户信息
            queryMerchInfo();
        }
//        if ((int) ClientEngine.getInstance().getGlobal(NoCardPayConstant.SHOWCRDITPAGE) == NoCardPayConstant.CREDITPAGE_VISIBITY && AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
//            ctv_smartpay.setVisibility(View.VISIBLE);
//            if (PreferenceManager.getInstance(_mActivity).getBoolean(NoCardPayConstant.SMART_PAY_TIPS_SHOW_MINE_VIEW, true)) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        showGuideTips(ctv_smartpay);
//                    }
//                }, 100);
//            }
//        }
        queryLotteryStatus();
    }


    /**
     * 获取当前用户信息
     */
    public void queryMerchInfo() {
//        HPLog.d(HPLog.SSX_TAG, "------------------查询商户信息请求-------------------");
        HPLog.d(HPLog.SSX_TAG, "accountName:" + AccountUtils.getAccountName(_mActivity));
        HashMap<String, Object> params = new HashMap<>();
        params.put(BaseProtocolKey.ACCOUNT, SecureManager.getInstance().des(AccountUtils.getAccountName(_mActivity), 1, null));
        params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        params.put(BaseProtocolKey.NEWBANKFLAG, newBankFlag);
        if (minePresenter != null) {
            minePresenter.getMerchInfo(params, MerchInfo.class, false);
        }
    }

    /**
     * 查询抽奖开关
     */
    public void queryLotteryStatus() {
        HashMap<String, Object> paramers = new HashMap<>();
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, NoCardPayConfig.CLIENTCHANNEL);
        paramers.put(BaseProtocolKey.CHANNEL, NoCardPayConfig.CHANNEL);
        if (minePresenter != null) {
            minePresenter.queryLotteryStatus(paramers, false);
        }
    }

    @Override
    public void querySuccess(MerchInfo merchInfo) {
//        HPLog.d(HPLog.SSX_TAG, "------------------查询商户信息返回-------------------");
        if (merchInfo == null) return;
        String name = SecureManager.getInstance().des(merchInfo.getName(), 0, null);
        String bankName = SecureManager.getInstance().des(merchInfo.getBankName(), 0, null);
        String cardNum = SecureManager.getInstance().des(merchInfo.getCardNum(), 0, null);
        String mSubBankName = SecureManager.getInstance().des(merchInfo.getSubBranchName(), 0, null);
        String certNo = SecureManager.getInstance().des(merchInfo.getCertNo(), 0, null);
        String mSubBankCode = merchInfo.getSubBankCode();//服务器未加密
//        HPLog.d(HPLog.SSX_TAG, "加密前 :" + merchInfo.toString());
        merchInfo.setName(name);
        merchInfo.setBankName(bankName);
        merchInfo.setCardNum(cardNum);
        merchInfo.setSubBranchName(mSubBankName);
        merchInfo.setSubBankCode(mSubBankCode);
//        HPLog.d(HPLog.SSX_TAG, "解密之后:" + merchInfo.toString());
        this.mMerchinfo = merchInfo;
        AccountUtils.saveUserName(_mActivity, name);
        AccountUtils.setAccountStatus(_mActivity, AccountUtils.convertStatus(merchInfo.getStatus()));
        String phone = SecureManager.getInstance().des(merchInfo.getPhone(), 0, null);
        AccountUtils.setAccountPhone(_mActivity, phone);
        AccountUtils.saveUsercertNo(_mActivity, certNo);
        merchInfoListener.refreshMerchInfo(merchInfo);

        //首次界面加载到内存的时候根据用户状态显示相应的界面
        if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.FAIL) {
            showHideFragment(mFragments[NO_QUALIFICATION], mFragments[YES_QUALIFICATION]);
        } else if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
            showHideFragment(mFragments[YES_QUALIFICATION], mFragments[NO_QUALIFICATION]);
        }
    }


    private View createTipsView() {
        View view = LayoutInflater.from(_mActivity).inflate(R.layout.layout_tips_view, null);
        return view;
    }


    private void showGuideTips(View view) {
        int[] loc = new int[2];
        view.getLocationOnScreen(loc);
        int y = (DisplayUtil.getScreenHeight(_mActivity) - loc[1]) * -1;
        View tipsView = createTipsView();
        if (easyGuide != null && easyGuide.isShowing())
            easyGuide.dismiss();

        easyGuide = new EasyGuide.Builder(_mActivity)
                // 增加View高亮区域，可同时显示多个
                .addHightArea(view, HShape.RECTANGLE)
                // 复杂的提示布局，建议通过此方法，较容易控制
                .addView(tipsView, 0, y, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
                // 若点击作用在高亮区域，是否执行高亮区域的点击事件
//                .performViewClick(true)
                .build();

        easyGuide.setOnStateChangedListener(new OnStateChangedListener() {
            @Override
            public void onShow() {

            }

            @Override
            public void onDismiss() {
                PreferenceManager.getInstance(_mActivity).putBoolean(NoCardPayConstant.SMART_PAY_TIPS_SHOW_MINE_VIEW, false);
            }
        });

        easyGuide.show();
    }


    @Override
    public void queryLotteryStatusFinsh(LotteryStatus lotteryStatus) {
        if (1 == lotteryStatus.getStatus()) {
            ctv_lottery.setVisibility(View.VISIBLE);
        } else {
            ctv_lottery.setVisibility(View.GONE);
        }
    }

    @Override
    public void detectedNotice(boolean flag) {
        mNotice.setLeftTvPaddingRightDrawableVisibility(flag);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        NoticePushFactory.with().unregisterNoticeListener(this);
    }
}
